using System;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Input;
using Crm2011.Framework.Connect;
using ScriptEase.Shell.Events;



namespace ScriptEase.Shell.Commands
{
    internal class CrmConnectCommand : ICommand
    {
        private readonly ShellViewModel _viewViewModel;



        public CrmConnectCommand(ShellViewModel viewViewModel)
        {
            _viewViewModel = viewViewModel;
        }



        public void Execute(object view)
        {
            ConnectionListView cnList = new ConnectionListView();
            cnList.Initialize();
            cnList.CurrentProfile = ConnectionList.Current.Items.FirstOrDefault(p => p.ConnectionId == _viewViewModel.Project.Data.ConnectionId);
            DialogResult result = cnList.ShowDialog();
            if (result == DialogResult.OK)
            {
                _viewViewModel.EventAggregator.GetEvent<ConnectionStringChangedEvent>().Publish(
                    new ConnectionStringChangedEventArgs(cnList.CurrentProfile.GetCrmConnectionString(), cnList.CurrentProfile.ConnectionId));
            }
        }



        public bool CanExecute(object parameter)
        {
            return ( _viewViewModel.ProjectLoadStatus == ProjectStatus.LoadedDisconnected);
        }



        public event EventHandler CanExecuteChanged;
    }
}